<template>
  <div class="todo-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="page-title">
            <el-icon class="title-icon"><List /></el-icon>
            待办事项
          </h1>
          <p class="page-subtitle">管理您的任务和计划</p>
        </div>
        <div class="header-right">
          <el-button
            type="primary"
            size="large"
            @click="addThing"
            class="add-btn"
          >
            <el-icon><Plus /></el-icon>
            添加任务
          </el-button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-container">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card total">
            <div class="stat-content">
              <el-icon class="stat-icon"><List /></el-icon>
              <div class="stat-info">
                <div class="stat-number">{{ todoList.length }}</div>
                <div class="stat-label">总任务数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card completed">
            <div class="stat-content">
              <el-icon class="stat-icon"><Check /></el-icon>
              <div class="stat-info">
                <div class="stat-number">{{ completedCount }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card pending">
            <div class="stat-content">
              <el-icon class="stat-icon"><Clock /></el-icon>
              <div class="stat-info">
                <div class="stat-number">{{ pendingCount }}</div>
                <div class="stat-label">待完成</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card progress">
            <div class="stat-content">
              <el-icon class="stat-icon"><TrendCharts /></el-icon>
              <div class="stat-info">
                <div class="stat-number">{{ progressPercentage }}%</div>
                <div class="stat-label">完成率</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 任务列表 -->
    <el-card class="todo-list-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">任务列表</span>
          <div class="card-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索任务..."
              class="search-input"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <div v-if="filteredTodoList.length === 0" class="empty-state">
        <el-empty description="暂无任务" :image-size="120">
          <el-button type="primary" @click="addThing">添加第一个任务</el-button>
        </el-empty>
      </div>

      <div v-else class="todo-items">
        <div
          v-for="todo in filteredTodoList"
          :key="todo.id"
          class="todo-item"
          :class="{ completed: todo.completed }"
        >
          <div class="todo-content">
            <div class="todo-checkbox">
              <el-checkbox
                :model-value="todo.completed"
                @change="() => toggleCompleted(todo.id)"
                size="large"
              />
            </div>
            <div class="todo-info">
              <div class="todo-title" :class="{ 'text-muted': todo.completed }">
                {{ todo.title }}
              </div>
              <div class="todo-meta">
                <el-tag
                  :type="todo.completed ? 'success' : 'warning'"
                  size="small"
                >
                  {{ todo.completed ? "已完成" : "进行中" }}
                </el-tag>
                <span class="todo-time">{{ formatTime(todo.createTime) }}</span>
              </div>
            </div>
            <div class="todo-actions">
              <el-button
                type="danger"
                size="small"
                text
                @click="deleteTodo(todo.id)"
                class="delete-btn"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 添加任务弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加新任务"
      width="500px"
      :before-close="handleClose"
      class="add-todo-dialog"
    >
      <InputThing @onSubmitSuccess="handleAddTodoSuccess" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/store/userStore";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  List,
  Plus,
  Check,
  Clock,
  TrendCharts,
  Search,
  Delete,
} from "@element-plus/icons-vue";
import request from "@/utils/request";
import InputThing from "@/components/InputThing.vue";

const router = useRouter();
const userStore = useUserStore();

const todoList = ref([]);
const dialogVisible = ref(false);
const searchQuery = ref("");

// 计算属性
const completedCount = computed(
  () => todoList.value.filter((todo) => todo.completed).length
);

const pendingCount = computed(
  () => todoList.value.filter((todo) => !todo.completed).length
);

const progressPercentage = computed(() => {
  if (todoList.value.length === 0) return 0;
  return Math.round((completedCount.value / todoList.value.length) * 100);
});

const filteredTodoList = computed(() => {
  if (!searchQuery.value) return todoList.value;
  return todoList.value.filter((todo) =>
    todo.title.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
});

// 方法
const addThing = () => {
  if (!userStore.isLoggedIn) {
    router.push("/login");
    ElMessage.warning("请先登录");
  } else {
    dialogVisible.value = true;
  }
};

const handleAddTodoSuccess = () => {
  dialogVisible.value = false;
  fetchTodoList();
  ElMessage.success("任务添加成功！");
};

const fetchTodoList = async () => {
  try {
    const data = await request.get("/api/todo");
    todoList.value = data;
  } catch (error) {
    console.error("获取待办事项失败", error);
    ElMessage.error("获取任务列表失败");
  }
};

const toggleCompleted = async (id) => {
  try {
    const gets = await request.patch(`/api/todo/${id}/toggle`);
    // ElMessage(gets);
    if (gets === false) {
      ElMessage.primary("任务已经完成了哦，就别继续想它啦");
    } else {
      ElMessage.success("任务状态已更新");
    }
    fetchTodoList();
  } catch (error) {
    console.error("切换状态失败", error);
    ElMessage.error("更新任务状态失败");
  }
};

const deleteTodo = async (id) => {
  try {
    await ElMessageBox.confirm("确定要删除这个任务吗？", "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await request.delete(`/api/todo/${id}`);
    fetchTodoList();
    ElMessage.success("任务已删除");
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败", error);
      ElMessage.error("删除任务失败");
    }
  }
};

const handleClose = (done) => {
  ElMessageBox.confirm("确定要关闭吗？未保存的内容将丢失")
    .then(() => {
      done();
    })
    .catch(() => {
      // 用户取消
    });
};

const formatTime = (timeString) => {
  const date = new Date(timeString);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

onMounted(() => {
  fetchTodoList();
});
</script>

<style scoped>
.todo-page {
  padding: 0;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40px 0;
  margin: -20px -20px 30px -20px;
  color: white;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.header-left {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 32px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-icon {
  font-size: 32px;
}

.page-subtitle {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
}

.add-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(10px);
  font-weight: 500;
}

.add-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
}

.stats-container {
  margin-bottom: 30px;
}

.stat-card {
  border: none;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  font-size: 32px;
  padding: 12px;
  border-radius: 12px;
}

.total .stat-icon {
  background: #e3f2fd;
  color: #1976d2;
}

.completed .stat-icon {
  background: #e8f5e8;
  color: #2e7d32;
}

.pending .stat-icon {
  background: #fff3e0;
  color: #f57c00;
}

.progress .stat-icon {
  background: #f3e5f5;
  color: #7b1fa2;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.todo-list-card {
  border: none;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.search-input {
  width: 300px;
}

.empty-state {
  padding: 60px 0;
  text-align: center;
}

.todo-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.todo-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.todo-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.todo-item.completed {
  background: #f8f9fa;
  border-color: #e9ecef;
}

.todo-content {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
}

.todo-checkbox {
  flex-shrink: 0;
}

.todo-info {
  flex: 1;
  min-width: 0;
}

.todo-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
  word-break: break-word;
}

.todo-title.text-muted {
  text-decoration: line-through;
  color: #909399;
}

.todo-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.todo-time {
  font-size: 12px;
  color: #909399;
}

.todo-actions {
  flex-shrink: 0;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  background: #fef0f0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }

  .page-title {
    font-size: 24px;
  }

  .search-input {
    width: 100%;
  }

  .stat-content {
    flex-direction: column;
    text-align: center;
    gap: 8px;
  }

  .stat-number {
    font-size: 24px;
  }
}
</style>
